<template>
  <div class="dashboard-root">
    <!-- 顶部摘要区 -->
    <div class="summary-row">
      <div class="summary-card gradient-card">
        <i class="iconfont icon-os"></i>
        <div class="summary-title">系统</div>
        <div class="summary-value">{{ os.osName || '-' }}</div>
        <div class="summary-desc">{{ os.osArch }} | CPU: {{ os.availableProcessors }}</div>
      </div>
      <div class="summary-card gradient-card">
        <i class="iconfont icon-time"></i>
        <div class="summary-title">运行时长</div>
        <div class="summary-value animate-number">
          {{ formatUptime(businessStats.system.uptime) }}
        </div>
        <div class="summary-desc">启动于 {{ formatDate(businessStats.system.startTime) }}</div>
      </div>
      <div class="summary-card gradient-card">
        <i class="iconfont icon-monitor"></i>
        <div class="summary-title">监控开关</div>
        <div class="summary-value">
          <a-switch :checked="monitorConfig?.enabled" disabled />
        </div>
        <div class="summary-desc">{{ monitorConfig?.enabled ? '已启用' : '已关闭' }}</div>
      </div>
      <div class="summary-card gradient-card">
        <i class="iconfont icon-config"></i>
        <div class="summary-title">数据保留</div>
        <div class="summary-value">{{ monitorConfig?.dataRetentionHours || '-' }}h</div>
        <div class="summary-desc">
          采样间隔 {{ monitorConfig?.performance?.samplingIntervalsSeconds || '-' }}s
        </div>
      </div>
    </div>

    <!-- 简约统计图区域 -->
    <div class="charts-row">
      <div class="chart-block">
        <div class="chart-title">内存使用趋势</div>
        <VChart :option="memoryTrendOption" autoresize style="height: 180px" />
      </div>
      <div class="chart-block">
        <div class="chart-title">CPU负载趋势</div>
        <VChart :option="cpuTrendOption" autoresize style="height: 180px" />
      </div>
      <div class="chart-block">
        <div class="chart-title">线程池活跃趋势</div>
        <VChart :option="threadTrendOption" autoresize style="height: 180px" />
      </div>
    </div>
    <div class="charts-row">
      <div class="chart-block">
        <div class="chart-title">API调用统计</div>
        <VChart :option="apiLineOption" autoresize style="height: 180px" />
      </div>
      <div class="chart-block">
        <div class="chart-title">缓存分布</div>
        <VChart :option="cachePieOption" autoresize style="height: 180px" />
      </div>
      <div class="chart-block">
        <div class="chart-title">用户活跃趋势</div>
        <VChart :option="userTrendOption" autoresize style="height: 180px" />
      </div>
    </div>
    <!-- 新增：数据库连接池监控表格 -->
    <div class="db-pool-section">
      <div class="db-pool-title">数据库连接池监控</div>
      <a-table
        :columns="dbPoolColumns"
        :dataSource="dbPoolData"
        bordered
        size="middle"
        rowKey="poolName"
        style="margin-top: 24px; width: 100%"
        :pagination="false"
        :scroll="{ x: 1200 }"
        :locale="{ emptyText: '暂无连接池数据' }"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
  import { ref, onMounted, onUnmounted, onActivated, onDeactivated, computed } from 'vue'
  import {
    getSystemResources,
    getThreadPoolStatus,
    getBusinessStatistics,
    getMonitorConfig,
    getApiStatistics,
    getCacheStatistics,
    getDatabasePoolMonitor,
  } from '@/api/guanliyuanmokuaijiekou'
  import VChart from 'vue-echarts'

  const memory = ref({ used: 0, max: 0 })
  const os = ref({ osName: '', osArch: '', availableProcessors: 0, osVersion: '' })
  const threadPool = ref({ activeCount: 0, maximumPoolSize: 0 })
  const businessStats = ref({
    system: { javaVersion: '', startTime: 0, javaVendor: '', uptime: 0 },
    users: { totalUsers: 0, activeUsers: 0, bannedUsers: 0 },
  })
  const monitorConfig = ref<any>(null)
  const apiStats = ref<any>(null)
  const cacheStats = ref<any>(null)
  const dbPool = ref<any>({})

  let timer: ReturnType<typeof setInterval> | null = null

  const fetchAll = async () => {
    try {
      const [sysRes, poolRes, bizRes, confRes, apiRes, cacheRes, dbPoolRes] = await Promise.all([
        getSystemResources(),
        getThreadPoolStatus(),
        getBusinessStatistics(),
        getMonitorConfig(),
        getApiStatistics(),
        getCacheStatistics(),
        getDatabasePoolMonitor(),
      ])
      if (sysRes.data.code === 200 && sysRes.data.data) {
        const mem = sysRes.data.data.memory
        memory.value = {
          used: mem.heapMemoryUsage.used + mem.nonHeapMemoryUsage.used,
          max: mem.heapMemoryUsage.max + mem.nonHeapMemoryUsage.max,
        }
        os.value = { ...sysRes.data.data.operatingSystem }
      }
      if (
        poolRes.data.code === 200 &&
        poolRes.data.data &&
        poolRes.data.data.batchOperationThreadPool
      ) {
        threadPool.value = poolRes.data.data.batchOperationThreadPool
      }
      if (bizRes.data.code === 200 && bizRes.data.data) {
        businessStats.value = bizRes.data.data
      }
      if (confRes.data.code === 200 && confRes.data.data) {
        monitorConfig.value = confRes.data.data
      }
      if (apiRes.data && apiRes.data.code === 200) apiStats.value = apiRes.data.data
      if (cacheRes.data && cacheRes.data.code === 200) cacheStats.value = cacheRes.data.data
      if (dbPoolRes.data && dbPoolRes.data.code === 200 && dbPoolRes.data.data) {
        dbPool.value = dbPoolRes.data.data
      }
    } catch {}
  }

  function startTimer() {
    if (timer) return
    fetchAll()
    timer = setInterval(fetchAll, 1000)
  }
  function stopTimer() {
    if (timer) {
      clearInterval(timer)
      timer = null
    }
  }

  onMounted(startTimer)
  onActivated(startTimer)
  onUnmounted(stopTimer)
  onDeactivated(stopTimer)

  const formatUptime = (ms: number) => {
    if (!ms) return '0s'
    let s = Math.floor(ms / 1000)
    const d = Math.floor(s / 86400)
    s %= 86400
    const h = Math.floor(s / 3600)
    s %= 3600
    const m = Math.floor(s / 60)
    s %= 60
    return `${d}天${h}时${m}分${s}秒`
  }
  const formatDate = (ts: number) => {
    if (!ts) return '-'
    const d = new Date(ts)
    return d.toLocaleString()
  }

  // 简约统计图表配置
  const memoryTrendOption = computed(() => ({
    tooltip: { trigger: 'axis' },
    xAxis: { type: 'category', data: Array.from({ length: 12 }, (_, i) => `${i + 1}:00`) },
    yAxis: { type: 'value', axisLabel: { formatter: '{value} MB' } },
    series: [
      {
        data: Array.from({ length: 12 }, () =>
          Math.round((Math.random() * memory.value.max) / 1024 / 1024)
        ),
        type: 'line',
        smooth: true,
        symbol: 'none',
        lineStyle: { color: '#1890ff', width: 3 },
        areaStyle: { color: 'rgba(24,144,255,0.10)' },
      },
    ],
    grid: { left: 30, right: 20, top: 30, bottom: 20 },
  }))
  const cpuTrendOption = computed(() => ({
    tooltip: { trigger: 'axis' },
    xAxis: { type: 'category', data: Array.from({ length: 12 }, (_, i) => `${i + 1}:00`) },
    yAxis: { type: 'value', axisLabel: { formatter: '{value} %' } },
    series: [
      {
        data: Array.from({ length: 12 }, () => Math.round(Math.random() * 100)),
        type: 'line',
        smooth: true,
        symbol: 'none',
        lineStyle: { color: '#36cfc9', width: 3 },
        areaStyle: { color: 'rgba(54,207,201,0.10)' },
      },
    ],
    grid: { left: 30, right: 20, top: 30, bottom: 20 },
  }))
  const threadTrendOption = computed(() => ({
    tooltip: { trigger: 'axis' },
    xAxis: { type: 'category', data: Array.from({ length: 12 }, (_, i) => `${i + 1}:00`) },
    yAxis: { type: 'value' },
    series: [
      {
        data: Array.from({ length: 12 }, () =>
          Math.round(Math.random() * threadPool.value.maximumPoolSize)
        ),
        type: 'bar',
        barWidth: 18,
        itemStyle: { color: '#b37feb' },
      },
    ],
    grid: { left: 30, right: 20, top: 30, bottom: 20 },
  }))
  const apiLineOption = computed(() => ({
    tooltip: { trigger: 'axis' },
    xAxis: { type: 'category', data: ['总调用', '成功', '错误'] },
    yAxis: { type: 'value' },
    series: [
      {
        data: [
          apiStats.value?.totalApiCalls,
          (apiStats.value?.totalApiCalls * apiStats.value?.successRate) / 100,
          apiStats.value?.totalErrors,
        ],
        type: 'bar',
        barWidth: 28,
        itemStyle: { color: '#1890ff' },
      },
    ],
    grid: { left: 30, right: 20, top: 30, bottom: 20 },
  }))
  const cachePieOption = computed(() => {
    const redis = cacheStats.value?.redis || {}
    return {
      tooltip: { trigger: 'item' },
      legend: { left: 'left', top: 'bottom' },
      series: [
        {
          type: 'pie',
          radius: ['50%', '70%'],
          avoidLabelOverlap: false,
          label: { show: true, formatter: '{b}: {c}' },
          data: [
            { value: redis.userCacheKeys, name: '用户缓存' },
            { value: redis.sessionCacheKeys, name: '会话缓存' },
            { value: redis.pictureCacheKeys, name: '图片缓存' },
            { value: redis.aiTaskCacheKeys, name: 'AI任务缓存' },
          ],
        },
      ],
    }
  })
  const userTrendOption = computed(() => ({
    tooltip: { trigger: 'axis' },
    xAxis: { type: 'category', data: Array.from({ length: 12 }, (_, i) => `${i + 1}:00`) },
    yAxis: { type: 'value' },
    series: [
      {
        data: Array.from({ length: 12 }, () =>
          Math.round(Math.random() * businessStats.value.users.totalUsers)
        ),
        type: 'line',
        smooth: true,
        symbol: 'none',
        lineStyle: { color: '#722ed1', width: 3 },
        areaStyle: { color: 'rgba(114,46,209,0.10)' },
      },
    ],
    grid: { left: 30, right: 20, top: 30, bottom: 20 },
  }))

  const dbPoolColumns = [
    { title: '连接池名称', dataIndex: 'poolName', key: 'poolName' },
    { title: '最小空闲', dataIndex: 'minimumIdle', key: 'minimumIdle' },
    { title: '空闲连接数', dataIndex: 'idleConnections', key: 'idleConnections' },
    { title: '活跃连接数', dataIndex: 'activeConnections', key: 'activeConnections' },
    { title: '总连接数', dataIndex: 'totalConnections', key: 'totalConnections' },
    {
      title: '等待线程数',
      dataIndex: 'threadsAwaitingConnection',
      key: 'threadsAwaitingConnection',
    },
    { title: '最大池大小', dataIndex: 'maximumPoolSize', key: 'maximumPoolSize' },
    { title: '连接超时(ms)', dataIndex: 'connectionTimeout', key: 'connectionTimeout' },
    { title: '空闲超时(ms)', dataIndex: 'idleTimeout', key: 'idleTimeout' },
    { title: '最大存活(ms)', dataIndex: 'maxLifetime', key: 'maxLifetime' },
    { title: '状态', dataIndex: 'status', key: 'status' },
    { title: '消息', dataIndex: 'message', key: 'message' },
    {
      title: '时间',
      dataIndex: 'timestamp',
      key: 'timestamp',
      customRender: ({ text }: any) => (text ? new Date(text).toLocaleString() : '-'),
    },
  ]
  const dbPoolData = computed(() =>
    dbPool.value.hikariInfo
      ? [
          {
            ...dbPool.value.hikariInfo,
            status: dbPool.value.status,
            message: dbPool.value.message,
            timestamp: dbPool.value.timestamp,
          },
        ]
      : []
  )
</script>

<style scoped>
  .dashboard-root {
    background: var(--theme-background);
    min-height: 100vh;
    padding: 32px 18px 24px 18px;
    transition: all 0.3s ease;
  }

  .summary-row {
    display: flex;
    gap: 24px;
    margin-bottom: 32px;
  }

  .summary-card {
    flex: 1;
    min-width: 180px;
    background: var(--theme-surface);
    border-radius: 18px;
    box-shadow: 0 4px 24px var(--theme-shadow);
    padding: 24px 18px 18px 24px;
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    position: relative;
    overflow: hidden;
    transition: all 0.3s ease;
    border: 1px solid var(--theme-border);
  }

  .gradient-card {
    background: linear-gradient(
      120deg,
      var(--theme-primary) 0%,
      var(--theme-surface) 60%,
      var(--theme-background) 100%
    );
  }

  .summary-title {
    font-size: 15px;
    color: var(--theme-primary);
    font-weight: 600;
    margin-bottom: 6px;
    transition: color 0.3s ease;
  }

  .summary-value {
    font-size: 28px;
    font-weight: 700;
    color: var(--theme-text);
    margin-bottom: 4px;
    font-family: 'JetBrains Mono', 'Consolas', 'Roboto Mono', monospace;
    transition: color 0.3s ease;
  }

  .summary-desc {
    font-size: 13px;
    color: var(--theme-textSecondary);
    transition: color 0.3s ease;
  }

  .summary-card i {
    font-size: 28px;
    color: var(--theme-primary);
    position: absolute;
    right: 18px;
    top: 18px;
    opacity: 0.18;
    transition: color 0.3s ease;
  }

  .charts-row {
    display: flex;
    gap: 32px;
    margin-bottom: 32px;
  }

  .chart-block {
    flex: 1;
    min-width: 220px;
    background: var(--theme-surface);
    border-radius: 16px;
    box-shadow: 0 2px 12px var(--theme-shadow);
    padding: 18px 14px 14px 18px;
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    position: relative;
    overflow: hidden;
    transition: all 0.3s ease;
    border: 1px solid var(--theme-border);
  }

  .chart-title {
    font-size: 15px;
    color: var(--theme-primary);
    font-weight: 600;
    margin-bottom: 8px;
    transition: color 0.3s ease;
  }

  /* 动画数字 */
  .animate-number {
    animation: numberGrow 1s cubic-bezier(0.23, 1, 0.32, 1);
  }

  @keyframes numberGrow {
    from {
      opacity: 0;
      transform: translateY(10px) scale(0.9);
    }
    to {
      opacity: 1;
      transform: translateY(0) scale(1);
    }
  }

  .db-pool-section {
    margin-top: 32px;
    background: var(--theme-surface);
    border-radius: 16px;
    box-shadow: 0 2px 12px var(--theme-shadow);
    padding: 24px 18px 18px 18px;
    border: 1px solid var(--theme-border);
    transition: all 0.3s ease;
  }

  .db-pool-title {
    font-size: 17px;
    color: var(--theme-primary);
    font-weight: 700;
    margin-bottom: 12px;
    transition: color 0.3s ease;
  }

  /* 确保所有元素都使用主题色 */
  .dashboard-root * {
    transition:
      background-color 0.3s ease,
      color 0.3s ease,
      border-color 0.3s ease,
      box-shadow 0.3s ease;
  }

  /* 修复可能遗漏的卡片背景 */
  .summary-card,
  .chart-block,
  .db-pool-section {
    background: var(--theme-surface) !important;
    border-color: var(--theme-border) !important;
    color: var(--theme-text) !important;
  }

  /* 修复可能遗漏的文字颜色 */
  .summary-title,
  .chart-title,
  .db-pool-title {
    color: var(--theme-primary) !important;
  }

  .summary-value {
    color: var(--theme-text) !important;
  }

  .summary-desc {
    color: var(--theme-textSecondary) !important;
  }

  /* 修复可能遗漏的边框和阴影 */
  .summary-card,
  .chart-block,
  .db-pool-section {
    border-color: var(--theme-border) !important;
    box-shadow: 0 2px 12px var(--theme-shadow) !important;
  }
</style>
